<?php
/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Gmap
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
class Gmap_Plugin_Signup_Location extends Core_Plugin_FormSequence_Abstract
{
  protected $_name = 'gmap';
  protected $_formClass = 'Gmap_Form_Signup_Location';
  protected $_script = array('signup/form/location.tpl', 'gmap');
  protected $_adminFormClass = 'Gmap_Form_Admin_Signup_Location';
  protected $_adminScript = array('admin-signup/location.tpl', 'gmap');
  protected $_skip;

  public function onSubmit(Zend_Controller_Request_Abstract $request)
  {
    // Form was valid
    $skip = $request->getParam("skip");
    // do this if the form value for "skip" was not set
    // if it is set, $this->setActive(false); $this->onsubmisvalue and return true.
    if( $skip == "skipForm" ) {
      $this->setActive(false);
      $this->onSubmitIsValid();
      $this->getSession()->skip = true;
      $this->_skip = true;
      return true;
    } else {
      parent::onSubmit($request);
    }
  }

  public function onProcess()
  {
    // In this case, the step was placed before the account step.
    // Register a hook to this method for onUserCreateAfter
    if( !$this->_registry->user ) {
      // Register temporary hook
      Engine_Hooks_Dispatcher::getInstance()->addEvent('onUserCreateAfter', array(
        'callback' => array($this, 'onProcess'),
      ));
      return;
    }
    $user = $this->_registry->user;
    
    $data = $this->getSession()->data;
    $form = $this->getForm();
    if( !$this->_skip && !$this->getSession()->skip ) {
      if( $form->isValid($data) ) {
        
        $values = $form->getValues();
        
        $table = Engine_Api::_()->getItemTable('gmap');
        $db = $table->getAdapter();
        $db->beginTransaction();
  
        try
        {

          // Create gmap
          $values = array_merge($values, array(
            'owner_type' => $user->getType(),
            'owner_id' => $user->getIdentity(),
            'featured' => 0,
            'sponsored' => 0,
            'home' => 1,
          ));

          
          $gmap = $table->createRow();
          $gmap->setFromArray($values);
          $gmap->populateGeocodedFields();
          $gmap->save();
        }

        catch( Exception $e )
        {
          $db->rollBack();
          throw $e;
        }

      }
    }
  }

  public function onAdminProcess($form)
  {
    $settings = Engine_Api::_()->getApi('settings', 'core');

    $step_table = Engine_Api::_()->getDbtable('signup', 'user');
    $step_row = $step_table->fetchRow($step_table->select()->where('class = ?', 'Gmap_Plugin_Signup_Location'));
    $step_row->enable = $form->getValue('enable');
    $step_row->save();

    $form->addNotice('Your changes have been saved.');
  }

}